import PackageAPI from '@/api/Package';
import { useReq } from '@/components';
import { Spin } from 'antd';
import React, { createContext, useContext, useEffect } from 'react';

const Context = createContext(null);

/**
 * 用packageCode获取所有计划和险种
 */
function PackageContext(props) {
  const { packageCode, children } = props;
  const xhr = useReq(PackageAPI.getByCode);
  const value = xhr.result?.data || null;

  useEffect(() => {
    if (packageCode) xhr.start(packageCode);
    return xhr.cancel;
  }, [packageCode]);

  return (
    <Spin spinning={xhr.status === 'loading'}>
      <Context.Provider value={value} children={children} />
    </Spin>
  );
}

/**
 * 子组件使用，获取packageData
 * @return {null|{plans:{requestProducts:{}[]}[]}}
 */
export function usePackageData() {
  return useContext(Context);
}

export default PackageContext;
